import { IParamsResult } from '@/shared/core/decorator/ListParams.decorator'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateUserDto } from './dto/create-user.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { UserEntity } from './entities/user.entity'

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  /**
   * 创建用户
   * @param dto
   */
  async create(dto: CreateUserDto) {
    const { username, password } = dto

    if (!username || !password) {
      return new HttpException('请输入用户名和密码', HttpStatus.BAD_REQUEST)
    }

    const user = await this.userRepository.findOne({ where: { username } })

    if (user) {
      return new HttpException('用户已存在', HttpStatus.BAD_REQUEST)
    }

    const newUser = await this.userRepository.create(dto)
    await this.userRepository.save(newUser)
    return newUser
  }

  /**
   * 用户登录
   * @param user
   */
  async login({ username, password }: CreateUserDto) {
    const user = await this.userRepository.findOne({
      select: ['id', 'username', 'password', 'cityId', 'nickName', 'status', 'email', 'phone', 'sex', 'birthday', 'customerLevel', 'appId'],
      where: { username },
    })

    if (!user || !(await UserEntity.comparePassword(password, user.password))) {
      return new HttpException('用户名或密码错误', HttpStatus.BAD_REQUEST)
    }

    if (!user.status) {
      return new HttpException('用户已锁定，无法登录', HttpStatus.BAD_REQUEST)
    }

    delete user?.password

    return user
  }

  /**
   * 列表
   * @param query 参数
   * @returns
   */
  findAll({ pageParams, where, order }: IParamsResult) {
    const { page, limit } = pageParams

    return this.userRepository.findAndCount({
      order,
      where,
      relations: ['roles'],
      skip: (page - 1) * limit,
      take: limit,
    })
  }

  async findOne(id) {
    return await this.userRepository.findOne({ where: { id }, relations: ['roles'] })
  }

  async findOneById(id) {
    return await this.userRepository.findOne({ where: { id } })
  }

  // 修改密码
  async updatePassword(id, dto) {
    const user = await this.findOneById(id)
    const { oldPassword, newPassword } = dto

    if (!user || !(await UserEntity.comparePassword(oldPassword, user.password))) {
      return new HttpException('用户名或密码错误', HttpStatus.BAD_REQUEST)
    }

    const hashNewPassword = UserEntity.encryptPassword(newPassword)
    const newUser = await this.userRepository.merge(user, {
      password: hashNewPassword,
    })

    const d = await this.userRepository.save(newUser)

    return d
  }

  // 修改指定用户
  async update(id, dto: UpdateUserDto) {
    const oldUser = await this.findOneById(id)
    delete dto.password

    const newUser = await this.userRepository.merge(oldUser, dto)
    return this.userRepository.save(newUser)
  }

  // 删除
  async remove(id) {
    const result = await this.userRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
